import { defineStore } from 'pinia';
import {ref, computed} from 'vue'
import {requestLogin, type LoginFormData} from '@/api/auth'

export const useAuthStore = defineStore('authStore', () => {
  const sessionIdRef = ref<string | null>(null)
  const isAuthenticated = computed(() => sessionIdRef.value !== null)

  async function loginAction(loginFormData: LoginFormData) {
    const sessionId = await requestLogin(loginFormData);
    sessionIdRef.value = sessionId;
    localStorage.setItem('sessionId', sessionId)
  }

  async function logoutAction(loginFormData: LoginFormData) {
    sessionIdRef.value = null;
    localStorage.removeItem('sessionId')
  }

  return { sessionIdRef, isAuthenticated, loginAction, logoutAction };
});

